const{Role,Op}=require('../model')

async function getAll(ctx,next){
    let keyword=ctx.request.query.keyword;
    let res={};
    if(keyword){
        res=await Role.findAll({
            where:{
            [Op.or]:[
                {
                    rolename:{
                        [Op.substring]:keyword
                    }
                },
                {
                    email:{
                        [Op.substring]:keyword
                    }
                }
            ]
            }
        })
    }else{
        res=await Role.findAll()
    }

    ctx.body=res;
}

async function getById(ctx,next){
    let id=ctx.request.params.id;
    let data=await Role.findByPk(id)

    ctx.body={
        code:1000,
        data:data,
        msg:"查询"
    }
}

async function addItem(ctx,next){
    let obj=ctx.request.body;
    await Role.create({
        rolename:obj.rolename,
        email:obj.email
    })

    ctx.body={
        code:1000,
        data:null,
        msg:'新镇'
    }
}

async function updateItem(ctx,next){
    let id =ctx.request.params.id;
    let obj=ctx.request.body;
    await Role.update({
        rolename:obj.rolename,
        email:obj.email
    },
    {
        where :{
            id:id
        }
    })
    ctx.body={
        code:1000,
        data:null,
        msg:'更新'
    }
}

async function deleteItem(ctx,next){
    let id=ctx.request.params.id;
    await Role.destroy({
        where:{
            id:id
        }
    })
    ctx.body={
        code:1000,
        data:null,
        msg:'删除'
    }
}

module.exports={
    'get /roles':getAll,
    'get /roles/:id':getById,
    'post /roles':addItem,
    'put /roles/:id':updateItem,
    'del /roles/:id':deleteItem
}